package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.common.constants.ArticleConstants;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.search.vos.SearchArticleVo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
@Transactional
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {

    @Autowired
    private Configuration configuration;
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private ApArticleMapper apArticleMapper;
    @Autowired
    private KafkaTemplate kafkaTemplate;

    /**
     * 生成静态文件上传到minIO中
     *
     * @param apArticle
     * @param content
     */
    @Override
    //异步调用,新建一个线程,跨类
    @Async
    public void buildArticleToMinIO(ApArticle apArticle, String content) {
        //1.访问数据库,获取文章内容
        //2.参数校验
        //3.文章内容通过freemarker生成html文件
        //3.1.拿到文章模板
        //3.2.提取文章的内容
        //3.3.合成process,并将页面数据写到输出流中
        //4.将html文件上传到minio
        //4.1通过字节输入流上传到minio,拿到返回的文件路径:path
        //5.将详情页的路径path回填到ap_article表的static_url字段上

        if (StringUtils.isNotEmpty(content)) {
            try {
                Template template = configuration.getTemplate("article.ftl");

                Map<String, Object> map = new HashMap<>();
                map.put("content", JSONArray.parseArray(content));  //字符串转json数组,集合

                //合成
                StringWriter sw = new StringWriter();
                template.process(map, sw);

                InputStream is = new ByteArrayInputStream(sw.toString().getBytes());
                String path = fileStorageService.uploadHtmlFile("", apArticle.getId() + ".html", is);

                //3. 将MinIO上传成功后返回的详情页url回填到数据库表：static_url属性上
                apArticleMapper.update(apArticle, Wrappers.<ApArticle>lambdaUpdate().eq(ApArticle::getId, apArticle.getId())
                        .set(ApArticle::getStaticUrl, path));

                //发送消息，创建索引
                createArticleESIndex(apArticle, content, path);

            } catch (Exception e) {
                e.printStackTrace();

            }


        }

    }

    /**
     * 发送消息创建索引
     */
    public void createArticleESIndex(ApArticle apArticle, String content, String path) {

        SearchArticleVo searchArticleVo = new SearchArticleVo();
        BeanUtils.copyProperties(apArticle, searchArticleVo);
        searchArticleVo.setContent(content);
        searchArticleVo.setStaticUrl(path);

        kafkaTemplate.send(ArticleConstants.ARTICLE_ES_SYNC_TOPIC, JSON.toJSONString(searchArticleVo));


    }
}
